<template>
    <div class="hc-container">
        <el-dialog v-dialogDrag v-if="popup" :close-on-click-modal="false" :title="text" style="text-align: left"
                   :visible.sync="popup"
                   width="40%">
            <div class="form-layer" v-loading="loading" element-loading-text="请稍等，地图加载中…">
                <el-form label-width="100px" size="mini">
                    <el-form-item label="获取定位">
                        <el-tag v-if="address" type="success">{{ address }}</el-tag>
                        <el-button type="primary" @click="fixedPos">重新定位</el-button>
                    </el-form-item>
                    <el-form-item label="当前纬度">
                        <div>{{ latitude }}</div>
                    </el-form-item>
                    <el-form-item label="当前经度">
                        <div>{{ longitude }}</div>
                    </el-form-item>
                    <el-form-item label="搜索位置">
                        <div class="f-a-c">
                            <el-input v-model="keyWords" placeholder="请输入地区" class="hc-custom-input"></el-input>
                            <el-button type="primary" @click="setPlace" :disabled="!keyWords">查询</el-button>
                        </div>
                    </el-form-item>
                    <el-form-item label="选择位置">
                        <div class="f-a-c">
                            <el-select @change="changeAddress" v-model="chooseAddress" class="hc-custom-input"
                                       filterable placeholder="请选择">
                                <el-option v-for="item in addressList" :key="item.value" :label="item.label"
                                           :value="item.value">
                                </el-option>
                            </el-select>
                        </div>
                    </el-form-item>
                </el-form>
                <div id="map-container"></div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" type="primary" @click="btnSubmit()">确 认</el-button>
                <el-button size="small" @click="popup = false">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
    import { TMapAddress, SearchAddress } from './TMap';
    export default {
        data()
        {
            return {
                popup: true, // 弹窗是否可见
                map: null, // 地图实例
                editor: null, // 编辑器
                marker: null,
                activeType: 'marker', // 激活的图形编辑类型
                local: null, // 地图本地搜索实例
                mk: null, // 标注实例
                latitude: '', // 维度
                longitude: '', // 经度
                keyWords: '', // 查询关键字
                text: '', // 弹窗标题
                address: '', // 地址
                loading: true, // 是否加载
                addressList: [], // 搜索出的地址集合
                chooseAddress: '' // select控件绑定的属性值
            };
        },
        methods: {
            // 打开弹窗，name为弹窗名称
            openDialog(showData, config)
            {
                config = config || {};
                this.text = config.name;
                this.popup = true;
                console.info(showData, "==============打开弹窗");
                // this.getLocation();
                // 异步加载地图
                const mapScript = document.createElement("script")
                mapScript.type = 'text/javascript'
                mapScript.src = 'https://map.qq.com/api/gljs?v=1.exp&key=KVZBZ-Y7BKJ-YJSFR-DPR2M-LRW5O-EIFW6'
                const mapToolScript = document.createElement("script")
                mapToolScript.type = 'text/javascript'
                mapToolScript.src = 'https://map.qq.com/api/gljs?v=1.exp&key=KVZBZ-Y7BKJ-YJSFR-DPR2M-LRW5O-EIFW6&libraries=tools'
                document.body.appendChild(mapScript)
                document.body.appendChild(mapToolScript)
                mapScript.onload = () => {
                    // 加载完成后初始化地图
                    this.initMap(showData);
                }
                // 创建promise
                return new Promise((resolve, reject) =>
                {
                    this.promiseStatus = {
                        resolve,
                        reject,
                    };
                });
            },
            // 确认
            btnSubmit()
            {
                let key = {
                    coordinate: {
                        latitude: this.latitude,
                        longitude: this.longitude,
                    },
                    address: this.address
                };
                // 打印经纬度
                // console.log(key);
                if (this.loading)
                {
                    this.$message('加载中，请稍后');
                    return;
                }
                this.popup = false;
                // 多选
                this.promiseStatus.resolve({
                    showData: key
                });
            },
            // 初始化地图
            initMap(showData)
            {
                this.$nextTick(() =>
                {
                    // 定义地图中心点坐标
                    var centerPoint = [30.153848, 114.995255]
                    var geometriesMarker = []
                    if (showData)
                    {
                        this.longitude = showData.coordinate.longitude;
                        this.latitude = showData.coordinate.latitude;
                        this.address = showData.address;
                        centerPoint = [this.latitude, this.longitude]
                        geometriesMarker.push({
                            "id": `marker`,
                            "styleId": 'myStyle', // 指定样式id
                            "position": new TMap.LatLng(this.latitude, this.longitude),// 点标记坐标位置
                            "properties": { // 自定义属性
                                "title": showData.address,
                            }
                        })
                    }
                    this.map = new TMap.Map(document.getElementById('map-container'), {
                        center: centerPoint, // 设置地图中心点坐标
                        zoom: 15.2,  // 设置地图缩放级别
                        // pitch: 43.5, // 设置俯仰角
                        // rotation: 45 // 设置地图旋转角度
                    })
                    this.loading = false;
                    this.marker = new TMap.MultiMarker({
                        map: this.map,
                        styles: {
                            "myStyle": new TMap.MarkerStyle({
                                "width": 25,
                                "height": 25
                            })
                        },
                    });
                    if (showData)
                    {
                        this.marker.add(geometriesMarker)
                    }
                    return
                    this.editor = new TMap.tools.GeometryEditor({
                        map: this.map,
                        overlayList: [
                            {
                                overlay: this.marker,
                                id: 'marker'
                            }
                        ],
                        actionMode: TMap.tools.constants.EDITOR_ACTION.DRAW, // 编辑器的工作模式
                        activeOverlayId: 'marker', // 激活图层
                        snappable: true,  // 开启吸附
                    })
                    // 监听绘制结束事件，获取绘制几何图形
                    this.editor.on('draw_complete', (geometry) => {
                        console.log(geometry, '绘制')
                        var id = geometry.id
                        if (this.editor.getActiveOverlay().id === 'marker')
                        {
                            var geo = this.marker.geometries.filter(item => item.id === id)
                            console.log(geo, '绘制的定位坐标')
                            this.latitude = geo[0].position.lat
                            this.longitude = geo[0].position.lng
                            var location = this.latitude.toFixed(6) + ',' + this.longitude.toFixed(6)
                            this.addressInfo(location)
                        }
                    })
                    return
                    let point = new BMap.Point(116.404, 39.915);
                    let zoom = 18;
                    if (showData)
                    { // 若有上一次设置的信息，则将上次的位置绘制到地图中
                        point = new BMap.Point(showData.coordinate.longitude, showData.coordinate.latitude);
                        zoom = 18;
                    }
                    this.map = new BMap.Map("map");
                    this.map.centerAndZoom(point, zoom);
                    this.map.enableScrollWheelZoom(true); // 开启鼠标滚轮缩放
                    this.map.addControl(new BMap.NavigationControl());
                    if (!showData)
                    {
                        this.fixedPos();
                    }
                    else
                    {
                        this.loading = false;
                        this.longitude = showData.coordinate.longitude;
                        this.latitude = showData.coordinate.latitude;
                        this.address = showData.address;
                        this.handleMarker(this, point);
                    }
                });
            },
            // 逆地址解析
            addressInfo(location)
            {
                TMapAddress(location).then(res => {
                    console.log(res, '地址')
                    if (res)
                    {
                        this.address = res.formatted_addresses.recommend || res.address
                    }
                })
            },
            // 点击定位-定位到当前位置
            fixedPos()
            {
                this.map.clearOverlays(); //清除地图上所有覆盖物
                const _this = this;
                if (!_this.loading)
                {
                    _this.loading = true;
                }
                _this.keyWords = '';
                _this.address = '';
                _this.latitude = '';
                _this.longitude = '';
                const geolocation = new BMapGL.Geolocation();
                geolocation.enableSDKLocation();
                geolocation.getCurrentPosition(function (r)
                {
                    // console.log(r,this)
                    if (this.getStatus() == BMAP_STATUS_SUCCESS)
                    {
                        // console.log('您的位置：', r, r.point.lng, r.point.lat);
                        let myGeo = new BMap.Geocoder();
                        myGeo.getLocation(
                            new BMap.Point(r.point.lng, r.point.lat),
                            function (result)
                            {
                                if (result)
                                {
                                    // console.log("============定位信息", result)
                                    _this.handleMarker(_this, result.point);
                                    _this.address = result.address;
                                    _this.latitude = result.point.lat;
                                    _this.longitude = result.point.lng;
                                    _this.loading = false;
                                }
                            }
                        );
                    }
                    else
                    {
                        _this.$message.error("failed" + this.getStatus());
                    }
                });
            },
            // 获取当前位置
            getLocation()
            {
                if (navigator.geolocation)
                {
                    navigator.geolocation.getCurrentPosition(function (position)
                    {
                        // console.log(position, "=======================position")
                    }, function (error)
                    {
                        // code：返回获取位置的状态
                        // 0  :  不包括其他错误编号中的错误
                        // 1  :  用户拒绝浏览器获取位置信息
                        // 2  :  尝试获取用户信息，但失败了
                        // ​3  :   设置了timeout值，获取位置超时了
                        // console.log(error, error.code, "==============错误码");
                    }, {
                        enableHighAcuracy: true,
                        timeout: 10000,
                        maximumAge: 10000
                    });
                }
                else
                {
                    alert("浏览器不支持地理定位。");
                }
            },
            // 搜索地址
            setPlace()
            {
                if (!this.loading)
                {
                    this.loading = true;
                }
                SearchAddress(this.keyWords).then(res => {
                    console.log(res, '搜索地址')
                    this.loading = false
                    if (res.length > 0)
                    {
                        this.addressList = []
                        var markerList = []
                        res.map((item, index) => {
                            var obj = {}
                            obj.id = `marker${index}`
                            obj.styleId = "myStyle"
                            obj.position = new TMap.LatLng(item.location.lat, item.location.lng),
                            obj.properties = {
                                "title": item.title,
                                "address": item.address
                            }
                            markerList.push(obj)
                            let point = {
                                title: item.title,
                                address: item.address,
                                latitude: item.location.lat,
                                longitude: item.location.lng
                            }
                            let address = {
                                label: item.title,
                                value: JSON.stringify(point),
                            };
                            this.addressList.push(address)
                        })
                        this.marker.add(markerList)
                    }
                    else
                    {
                        this.$message.error("未匹配到地点!");
                        this.loading = false;
                    }
                })
                return
                this.local = new BMap.LocalSearch(this.map, {
                    onSearchComplete: this.searchPlace,
                    pageCapacity: 100
                });
                this.local.search(this.keyWords);
            },
            // 搜索地址的回调
            searchPlace()
            {
                if (this.local.getResults() != undefined && this.local.getResults().getCurrentNumPois() != 0)
                {
                    this.map.clearOverlays(); //清除地图上所有覆盖物
                    this.addressList = []
                    for (let i = 0; i < this.local.getResults().getCurrentNumPois(); i++)
                    {
                        let pointAddress = this.local.getResults().getPoi(i);
                        // console.log(pointAddress, "===============", i);
                        //  
                        let point = {
                            title: pointAddress.title,
                            address: pointAddress.address,
                            latitude: pointAddress.point.lat,
                            longitude: pointAddress.point.lng,
                        };
                        let address = {
                            label: pointAddress.title,
                            value: JSON.stringify(point),
                        };
                        this.addressList.push(address);
                    }
                    if (this.local.getResults().getPoi(0))
                    {
                        let addressInfo = this.local.getResults().getPoi(0);
                        this.map.centerAndZoom(addressInfo.point, 18);
                        this.handleMarker(this, addressInfo.point);
                        this.address = addressInfo.address;
                        this.latitude = addressInfo.point.lat;
                        this.longitude = addressInfo.point.lng;
                        this.chooseAddress = JSON.stringify({
                            title: addressInfo.title,
                            address: addressInfo.address,
                            latitude: addressInfo.point.lat,
                            longitude: addressInfo.point.lng,
                        });
                        this.loading = false;
                    }
                    else
                    {
                        this.$message.error("未匹配到地点!");
                        this.loading = false;
                    }
                }
                else if (local.getResults().Cr.length == 0)
                {
                    this.$message.error("请您精确搜索内容");
                    this.loading = false;
                }
                else
                {
                    this.$message.error("未找到搜索结果!");
                    this.loading = false;
                }
            },
            // 设置标注
            handleMarker(obj, point)
            {
                let that = this;
                // console.log(point, "==================point");
                obj.mk = new BMap.Marker(point);
                obj.map.addOverlay(obj.mk);
                obj.mk.enableDragging(); // 可拖拽
                obj.mk.addEventListener("dragend", function (e)
                {
                    // console.log(e)
                    // 监听标注的拖拽，获取拖拽后的经纬度
                    that.latitude = e.point.lat;
                    that.longitude = e.point.lng;
                    var myGeo = new BMap.Geocoder({extensions_town: true});
                    let point = new BMap.Point(that.longitude, that.latitude);
                    // 根据坐标得到地址描述
                    myGeo.getLocation(point, function (result)
                    {
                        if (result)
                        {
                            // console.log(result.address);
                            if (result.address)
                            {
                                that.address = result.address;
                            }
                        }
                    });
                });
                obj.map.panTo(point);
            },
            // 下拉选择搜索出的地址
            changeAddress(data)
            {
                let addressInfo = JSON.parse(data);
                console.log(addressInfo, 'addressInfo')
                // 修改中心点
                this.map.setCenter(new TMap.LatLng(addressInfo.latitude, addressInfo.longitude))
                this.marker.setGeometries([]) // 清楚标记点
                this.marker.add([
                    {
                        "id": "marker",
                        "styleId": "myStyle",
                        "position": new TMap.LatLng(addressInfo.latitude, addressInfo.longitude)
                    }
                ])
                // let point = new BMap.Point(addressInfo.longitude, addressInfo.latitude)
                // this.map.clearOverlays(); //清除地图上所有覆盖物
                // this.map.centerAndZoom(point, 18);
                // this.handleMarker(this, point);
                this.longitude = addressInfo.longitude;
                this.latitude = addressInfo.latitude;
                this.address = addressInfo.address;
            },
        },
    }

</script>
<style lang="scss" scoped>
    .hc-container .form-layer {
        width: 100%;
    }

    .hc-container #map {
        margin-top: 30px;
        width: 100%;
        height: 300px;
        border: 1px solid gray;
        box-sizing: border-box;
        overflow: hidden;
    }

    .hc-container {
        ::v-deep .el-dialog {
            min-width: 550px;
        }
    }

    .hc-container {
        ::v-deep .el-dialog__body {
            padding: 10px;
        }

        ::v-deep .el-tag.el-tag--success {
            margin: 0px 10px 0px 0px;
        }
    }

    .hc-custom-input {
        width: 230px;
        margin-right: 6px;
    }

    #map {
        position: relative;
    }
    #toolControl {
        position: absolute;
        top: 10px;
        left: 0px;
        right: 0px;
        margin: auto;
        width: 252px;
        z-index: 1001;
    }
    .toolItem {
        width: 30px;
        height: 30px;
        float: left;
        margin: 1px;
        padding: 4px;
        border-radius: 3px;
        background-size: 30px 30px;
        // background-position: 4px 4px;
        background-repeat: no-repeat;
        box-shadow: 0 1px 2px 0 #e4e7ef;
        background-color: #ffffff;
        border: 1px solid #ffffff;
    }
    .toolItem:hover {
        border-color: #789cff;
    }
    .active {
        border-color: #d5dff2;
        background-color: #d5dff2;
    }
    #marker {
        background-image: url('https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/marker_editor.png');
    }
</style>